package com.iasku.iaskueleclass_phone.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.HashMap;

import org.kobjects.base64.Base64;
import org.ksoap2.serialization.SoapObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.iasku.constant.Constant;
import com.iasku.iaskueleclass_phone.R;
import com.iasku.loadimg.MyImageLoader;
import com.iasku.manager.ExitManager;
import com.iasku.util.BaseUtil;
import com.iasku.util.SoapUtil;
import com.iasku.view.RoundedCornerImageView;

/**
 * 用户设置
 */
public class UserSettingActivity extends Activity {
    private ImageButton btnBack;
    private Button btnCommit;
    private RoundedCornerImageView ivHead;
    private EditText etTruename, etPhone, etEmail;
    private EditText etOldPass, etNewPass, etNewPass2;
    private Button btnExit;
    private Editor editor;
    private RelativeLayout btnModifyHeadImg;
    private ProgressDialog pDialog;
    private Bitmap headBmp;
    private int screenWidth;
    private AlertDialog imgAlertDialog;
    private String img_type;
    private String oldPass,newPass,truename;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case 1:
                getHeadImg(msg);
                break;
            case -1:
                pDialog.dismiss();
                break;
            case 2:
                updateInfoOk(msg);
                break;
            }
        }
    };
    
    @SuppressWarnings("unchecked")
    private void updateInfoOk(Message msg) {
        pDialog.dismiss();
        HashMap<String, Object> map = (HashMap<String, Object>) msg.obj;
        Object value1 = map.get("submit_info");
        Object value2 = map.get("submit_img");
        Object value3 = map.get("submit_pass");
        if (value1 != null) {
            String result1 = value1.toString();
            if (Integer.parseInt(result1) > 0) {
                if (value2 != null && value3 == null) {
                    String result2 = value2.toString();
                    if (!result2.contains("anyType")) {
                        setHeadImg();
                        Constant.USER_TRUENAME = truename;
                        BaseUtil.showText(this, "提交信息成功");
                    } else {
                        BaseUtil.showText(this, "头像提交失败");
                    }
                } else if (value2 == null && value3 != null) {
                    String result3 = value3.toString();
                    if ("1".equals(result3)) {
                        logout();
                        BaseUtil.showText(this, "提交信息成功");
                    } else if ("0".equals(result3)) {
                        BaseUtil.showText(this, "原密码输入有误");
                    }
                } else if (value2 == null && value3 == null) {
                    Constant.USER_TRUENAME = truename;
                    BaseUtil.showText(this, "提交信息成功");
                } else if (value2 != null && value3 != null) {
                    String result2 = value2.toString();
                    String result3 = value3.toString();
                    if (!result2.contains("anyType") && "1".equals(result3)) {
                        setHeadImg();
                        BaseUtil.showText(this, "提交信息成功");
                        logout();
                    } else {
                        BaseUtil.showText(this, "提交信息失败");
                    }
                }
            } else {
                BaseUtil.showText(this, "提交信息失败");
            }
        } else {
            BaseUtil.showText(this, "提交信息失败");
        }
    }
    
    private void setHeadImg(){
        Bitmap bmp = Bitmap.createScaledBitmap(headBmp, screenWidth / 8, screenWidth / 8, false);
        ivHead.setImageBitmap(bmp);
    }

    private void getHeadImg(Message msg) {
        pDialog.dismiss();
        headBmp = (Bitmap) msg.obj;
        setHeadImg();
    }

    private void initDialog() {
        pDialog = new ProgressDialog(this);
    }

    private void setupView() {
        btnBack = (ImageButton) findViewById(R.id.btn_modify_back);
        btnCommit = (Button) findViewById(R.id.btn_modify_commit);
        btnModifyHeadImg = (RelativeLayout) findViewById(R.id.btn_modify_headimg);
        ivHead = (RoundedCornerImageView) findViewById(R.id.iv_modify_headimg);
        etTruename = (EditText) findViewById(R.id.et_modify_truename);
        etPhone = (EditText) findViewById(R.id.et_modify_phone);
        etEmail = (EditText) findViewById(R.id.et_modify_email);
        etOldPass = (EditText) findViewById(R.id.et_modify_oldpass);
        etNewPass = (EditText) findViewById(R.id.et_modify_newpass);
        etNewPass2 = (EditText) findViewById(R.id.et_modify_newpass2);
        btnExit = (Button) findViewById(R.id.btn_modify_exit);
    }

    private void addListener() {
        MyOnClickListner listener = new MyOnClickListner();
        btnBack.setOnClickListener(listener);
        btnCommit.setOnClickListener(listener);
        btnModifyHeadImg.setOnClickListener(listener);
        btnExit.setOnClickListener(listener);
    }

    private void init() {
        ExitManager.getExitManager().addActivity(this);
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
        editor = pref.edit();
        setupView();
        etTruename.setText(Constant.USER_TRUENAME);
        addListener();
        initDialog();
        pDialog.show();
        new Thread(getUserHeadImg).start();
    }

    private Runnable getUserHeadImg = new Runnable() {
        @Override
        public void run() {
            String methodname = "GetSchoolUserHeaderImg";
            String resultLog = methodname + Constant.RESULT;
            HashMap<String, String> params = new HashMap<String, String>();
            params.put("iaskuuname",Constant.USER_IASKUNAME);
            SoapObject res = SoapUtil.getResponseSoapObject(params,methodname,Constant.NAMESPACE2,Constant.URL2);
            if (res != null) {
                String value = res.getProperty(resultLog).toString();
                if (!value.startsWith("anyType")) {
                    MyImageLoader loader = new MyImageLoader(UserSettingActivity.this);
                    loader.setSaveDir(Constant.SAVE_HEADIMG_DIR);
                    Bitmap bmp = loader.loadHeadImage(value);
                    Message msg = Message.obtain();
                    msg.what = 1;
                    msg.obj = bmp;
                    mHandler.sendMessage(msg);
                } else {
                    mHandler.sendEmptyMessage(-1);
                }
            }
        }
    };

    private Runnable submit_info = new Runnable() {
        @Override
        public void run() {
            HashMap<String, Object> map = new HashMap<String, Object>();
            if (img_type != null && !"".equals(img_type)) {
                submitImg(map);
            }
            if (!"".equals(oldPass) && !"".equals(newPass)) {
                submitNewPass(map);
            }
            submitInfo(map);
            Message msg = Message.obtain();
            msg.what = 2;
            msg.obj = map;
            mHandler.sendMessage(msg);
        }
    };
    
    private void submitImg(HashMap<String, Object> map) {
        String methodname = "UploadHeadJpg";
        String resultLog = methodname + Constant.RESULT;
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("userid", Constant.USER_IASKUNAME);
        params.put("ss", img_type);
        SoapObject res = SoapUtil.getResponseSoapObject(params, methodname, Constant.NAMESPACE2 , Constant.URL2);
        map.put("submit_img", res.getProperty(resultLog));
    }
    
    private void submitInfo(HashMap<String, Object> map) {
        String methodname = "UpdateSchoolUserInfo";
        String resultLog = methodname + Constant.RESULT;
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("userid", Constant.USER_IASKUNAME);
        params.put("truename", truename);
        params.put("tel", etPhone.getText().toString().trim());
        params.put("email", etEmail.getText().toString().trim());
        SoapObject res = SoapUtil.getResponseSoapObject(params, methodname, Constant.NAMESPACE2 , Constant.URL2);
        map.put("submit_info", res.getProperty(resultLog));
    }

    private void submitNewPass(HashMap<String, Object> map) {
        String methodname = "AppUserChangePassword";
        String resultLog = methodname + Constant.RESULT;
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("userid", Constant.USER_IASKUNAME);
        params.put("oldpassword", oldPass);
        params.put("newpassword", newPass);
        SoapObject res = SoapUtil.getResponseSoapObject(params, methodname, Constant.NAMESPACE3 , Constant.URL3);
        map.put("submit_pass", res.getProperty(resultLog));
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_modify);
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        screenWidth = dm.widthPixels;
        init();
    }
    
    private void setPicToView(Intent picdata) {
        Bundle extras = picdata.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            /**
             * 下面注释的方法是将裁剪之后的图片以Base64Coder的字符方式上 传到服务器，QQ头像上传采用的方法跟这个类似
             */
            Bitmap temp = Bitmap.createScaledBitmap(photo, 100, 100, false).copy(Config.ARGB_8888, false);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            temp.compress(Bitmap.CompressFormat.JPEG, 100, stream);
            photo.recycle();
            byte[] b = stream.toByteArray();
            // 将图片流以字符串形式存储下来
            img_type = new String(Base64.encode(b));
            headBmp = temp;
            setHeadImg();
        }
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            // 如果是直接从相册获取
            case 1:
                if (data != null) {
                    if (data.getData() != null) {
                        startPhotoZoom(data.getData());
                    }
                }
                break;
            // 如果是调用相机拍照时
            case 2:
                File temp = new File(Environment.getExternalStorageDirectory() + Constant.HEAD_PIC_NAME);
                startPhotoZoom(Uri.fromFile(temp));
                break;
            // 取得裁剪后的图片
            case 3:
                /** 非空判断大家一定要验证，如果不验证的话， 在剪裁之后如果发现不满意，要重新裁剪，丢弃 当前功能时，会报NullException */
                if (data != null) {
                    setPicToView(data);
                }
                break;

            }
            super.onActivityResult(requestCode, resultCode, data);
        
    }

    private void startPhotoZoom(Uri uri) {
        /*
         * 至于下面这个Intent的ACTION是怎么知道的，大家可以看下自己路径下的如下网页
         * yourself_sdk_path/docs/reference/android/content/Intent.html
         */
        // DisplayMetrics dm=new DisplayMetrics();
        // getWindowManager().getDefaultDisplay().getMetrics(dm);
        int w = screenWidth / 3;
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 0.5);
        intent.putExtra("aspectY", 0.5);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", w);
        intent.putExtra("outputY", w);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);
    }
    
    private class MyOnClickListner implements OnClickListener {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.btn_modify_back: // 返回
                finish();
                break;
            case R.id.btn_modify_commit: // 提交
                submit_userinfo();
                break;
            case R.id.btn_modify_headimg: // 头像
                modify_headimg();
                break;
            case R.id.btn_modify_exit: // 退出登录
                user_exit();
                break;
            }
        }
    }

    /** 提交个人信息 */
    private void submit_userinfo() {
        oldPass = etOldPass.getText().toString().trim();
        newPass = etNewPass.getText().toString().trim();
        if (BaseUtil.isEmptyEt(etTruename)) {
            BaseUtil.showText(this, "真实姓名不能为空");
            return;
        }
        truename = etTruename.getText().toString().trim();
        String newPass2 = etNewPass2.getText().toString().trim();
        if (!"".equals(oldPass)) {
            if ("".equals(newPass)) {
                BaseUtil.showText(this, "新密码不能为空");
                return;
            } else if (!newPass.equals(newPass2)) {
                BaseUtil.showText(this, "两次密码输入不一致");
                return;
            }
        }
        String email = etEmail.getText().toString().trim();
        if(!"".equals(email)){
            if(!email.matches(Constant.MATCHES_EMAIL)){
                BaseUtil.showText(this, "邮箱格式不正确");
                return;
            }
        }
        pDialog.setMessage("正在提交");
        pDialog.show();
        new Thread(submit_info).start();
    }
    
    

    private void showImgDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.headimg_dialog, null);
        builder.setView(view);
        imgAlertDialog = builder.create();
        LinearLayout btnLocal = (LinearLayout) view.findViewById(R.id.btn_headimg_local);
        LinearLayout btnCamera = (LinearLayout) view.findViewById(R.id.btn_headimg_camera);
        btnLocal.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                imgAlertDialog.dismiss();
                Intent getImage = new Intent(Intent.ACTION_GET_CONTENT);
                getImage.addCategory(Intent.CATEGORY_OPENABLE);
                getImage.setType("image/*");
                startActivityForResult(getImage, 1);
            }
        });

        btnCamera.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                imgAlertDialog.dismiss();
                // TODO Auto-generated method stub
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                // 下面这句指定调用相机拍照后的照片存储的路径
                intent.putExtra(MediaStore.EXTRA_OUTPUT,
                        Uri.fromFile(new File(Environment.getExternalStorageDirectory(), Constant.HEAD_PIC_NAME)));
                startActivityForResult(intent, 2);
            }
        });
        imgAlertDialog.show();
    }

    /** 修改个人头像 */
    private void modify_headimg() {
        showImgDialog();
    }

    /** 退出登录 */
    private void user_exit() {
        showLogoutDialog();
    }

    private void showLogoutDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage("是否退出当前账号?");
        builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                logout();
            }
        });
        builder.setNegativeButton("否", null);
        builder.create().show();
    }

    private void logout() {
        editor.putBoolean(Constant.EDIT_USERISLOG, false);
        editor.commit();
        Intent intent = new Intent();
        intent.setClass(this, UserLoginActivity.class);
        startActivity(intent);
        ExitManager.getExitManager().exitActivities();
    }
}
